package leetcode.new_wrold;

import java.util.Arrays;

public class T16 {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int length = nums.length;
        int finalTotal = (int) Math.pow(10,5);
        //双指针减少一重循环
        for (int i=0;i<length;i++){
            if (i>0 && nums[i]==nums[i-1]){
                continue;
            }

            int l = i+1,r = length-1;
            while (l<r){
                int sum = nums[i]+nums[l]+nums[r];
                System.out.print("sum="+sum);
                if (sum==target){
                    return target;
                }
                if (Math.abs(sum-target)<Math.abs(finalTotal-target)){
                    finalTotal = sum;
                }

                if (sum>target){
                    do {
                        --r;
                    }while (l<r&&nums[r]==nums[r+1]);   //跳过相同的
                    System.out.println("r--到"+r);
                }else {
                    do {
                        ++l;
                    }while (l<r && nums[l]==nums[l-1]);
                    System.out.println("l++到"+l);
                }
            }
        }
        return finalTotal;
    }



    public static void main(String[] args) {
        T16 t16 = new T16();
        int ans = t16.threeSumClosest(new int[]{-1,0,1,1,55}, 3);
        System.out.println(ans);
    }
}
